<?php

use mytharcher\sdk\alipay\Alipay;
require_once LIB_PATH.'/TpFrame/Extend/Vendor/WxPay/AutoLoad.php';


class OrderCheckAction extends Action{
	
	function test(){
		echo 1;
// 		/OrderCheck/OrderCheck/order_no/100748350
	}
	
	function Notify(){
// 		Vendor('WxPay.AutoLoad','.php');
		$logHandler= new CLogFileHandler(LOG_PATH."/Pay-".date('Y-m').'.log');
		$log = PayLog::Init($logHandler, 15);
		$notify = new PayNotifyCallBack();
		$notify->Handle(false);
		
	}
	
	

	
	function AliNotify(){
		global $AlipayPayLog;
		ini_set("display_errors", "On");
		error_reporting(E_ALL | E_STRICT);
		
	    $logHandler= new CLogFileHandler(LOG_PATH."/Alipay-".date('Y-m').'.log');
	    $AlipayPayLog = PayLog::Init($logHandler, 15);
	    
		$alipay = new Alipay([
		    'partner'      => C("ALIPAY_PARTNER"),
		    'key'          => C("ALIPAY_KEY"),
		    'seller_email' => C("ALIPAY_EMAIL")
    	],'wap');
		// 获得验证结果 true/false
		$result = $alipay->verifyCallback($AlipayPayLog);
		if($result===true){
			$order_no = $_POST['out_trade_no'];
			$trade_no = $_POST['trade_no'];
			$trade_status = $_POST['trade_status'];
			$amount = $_POST['total_fee'];
			$this->OrderPaySuccess($order_no, '支付宝支付', $amount, $_POST);
		}else{
			
		}
	}
	
	
	
	
	
	
	
	//业绩结算
	function OrderCheck($order_no){
		
		exit();
		if(empty($order_no)){
			$order_no = $_GET['order_no'];
		}
		
		$oo = M("csl_order");
		
		$oinfo = $oo->where(
				array('order_no'=>$order_no,'order_status'=>array('egt','7'),'check'=>'0')
		)->find();
	
		if(empty($oinfo)){
			//未找到需要结算的订单
			return ;
		}
		
// 		ID: 27612
// 		【互云脉片】恭喜您已成功下单，客服人员会尽快与您联系，
// 		确定您名片的内容，请耐心等待。祝您使用愉快！咨询电话#code#。
		CommonFunc::SendComSMS('27612', $oinfo['shipping_mobile'], '0592-5127572');
		
		$oo->where(
				array('order_no'=>$order_no,'order_status'=>array('egt','7'),'check'=>'0')
		)->setField('check', '1');
	
		$oc = M("csl_customer");
		$me = $oc->where(array('cid'=>$oinfo['cid']))->find();
		if(empty($me)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "业绩分配出错，未找到订单所有者信息。");
			$this->OrderCheckAgency($oinfo,0);
			return ;
		}
	
		$parent1 = $oc->where(array('cid'=>$me['parentcid']))->find();
		if(empty($parent1)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "分销商业绩分配完毕");
			$this->OrderCheckAgency($oinfo,0);
			return ;
		}
		
		$this->CustomerAward($parent1, $oinfo, 15 , 200);
	
		$parent2 = $oc->where(array('cid'=>$parent1['parentcid']))->find();
		if(empty($parent2)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "分销商业绩分配完毕");
			$this->OrderCheckAgency($oinfo,1);
			return ;
		}
		
		$this->CustomerAward($parent2, $oinfo, 20 , 250);
		
		
		$parent3 = $oc->where(array('cid'=>$parent2['parentcid']))->find();
		if(empty($parent3)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "分销商业绩分配完毕");
			$this->OrderCheckAgency($oinfo,2);
			return ;
		}
		
		$this->CustomerAward($parent3, $oinfo, 25 , 300);
		LogTransactionModel::ModifyInventory
			('', $oinfo[order_no], '订单业绩分配', "分销商业绩分配完毕");
		$this->OrderCheckAgency($oinfo,3);
	
	}
	
	function OrderCheckAgency($oinfo,$level){
		$ou = M("csl_user");
		
		$uinfo = $ou->where(array('uid'=>$oinfo['uid'],'status'=>'1'))->find();
		if(empty($uinfo)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "代理商业绩分配完毕，没有找到核心/官方代理");
			return ;
		}
		
		
		
		
		
		if($level == 0){
			$money = 75;
			$point = 150;
		}elseif($level == 1){
			$money = 60;
			$point = 150;
		}elseif($level == 2){
			$money = 40;
			$point = 150;
		}elseif($level == 3){
			$money = 15;
			$point = 150;
		}else{
			$money = 0;
			$point = 0;
		}
		
		$this->UserAward($uinfo, $oinfo, $money, $point);
		
		$invite = $ou->where(array('uid'=>$uinfo['invite_uid'],'status'=>'1'))->find();
		if(!empty($invite)){
			$this->UserAward($invite, $oinfo, 5, 0);
		}else{
			LogTransactionModel::ModifyInventory
			('', $oinfo[order_no], '订单业绩分配', "代理商业绩分配完毕，没有找到邀请人");
		}
		$parent1 = $ou->where(array('uid'=>$uinfo['puid'],'status'=>'1'))->find();
		if(empty($parent1)){
			LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "代理商业绩分配完毕，没有找到上级代理");
			if($uinfo['rid']=='5'){
				//自己是官方代理
				$parent_invite = $ou->where(array('uid'=>$uinfo['invite_uid'],'status'=>'1'))->find();
				if(empty($parent_invite)){
					LogTransactionModel::ModifyInventory
					('', $oinfo[order_no], '订单业绩分配', "官方代理商业绩分配，没有找到邀请人代理商");
				}else{
					$this->UserAward($parent_invite, $oinfo, 2, 0);
				}
				
			}
				
		}else{
			$this->UserAward($parent1, $oinfo, 35, 100);
			if($parent1['rid']=='5'){
				$parent_invite = $ou->where(array('uid'=>$parent1['invite_uid'],'status'=>'1'))->find();
				if(empty($parent_invite)){
					LogTransactionModel::ModifyInventory
					('', $oinfo[order_no], '订单业绩分配', "官方代理商业绩分配，没有找到邀请人代理商");
				}else{
					$this->UserAward($parent_invite, $oinfo, 2, 0);
				}
			}
		}
		
		
		if($uinfo['rid']=='5' && $uinfo['city'] != $oinfo['shipping_city']
				&& !empty($oinfo['shipping_city'])){
			
			$cityAgent = $ou->where(array('rid'=>'5','city'=>$oinfo['shipping_city'],'status'=>'1'))->find();
			if($cityAgent){
				$this->UserCityAward($uinfo, $oinfo, -5, 0);
				$this->UserCityAward($cityAgent, $oinfo, 5, 0);
			}else{
				LogTransactionModel::ModifyInventory
				('', $oinfo[order_no], '订单业绩分配', "跨城市业绩分配完毕");
			}
		}else{
			$parent1 = $ou->where(array('uid'=>$uinfo['puid']))->find();
			if($parent1['rid']=='5' && $parent1['city'] != $oinfo['shipping_city']
					&& !empty($oinfo['shipping_city'])){
		
				$cityAgent = $ou->where(array('rid'=>'5','city'=>$oinfo['shipping_city'],'status'=>'1'))->find();
				if($cityAgent){
					$this->UserCityAward($parent1, $oinfo, -5, 0);
					$this->UserCityAward($cityAgent, $oinfo, 5, 0);
				}else{
					LogTransactionModel::ModifyInventory
					('', $oinfo[order_no], '订单业绩分配', "跨城市业绩分配完毕");
				}
			}
		}
		
	}
	
	function CustomerAward($customer,$oinfo,$money,$point){
		
		$oc = M("csl_customer");
		
		$save['money'] = $customer['money'] + $money * $oinfo['number'];
		$save['point'] = $customer['point'] + $point * $oinfo['number'];
		$oc->where(array('cid'=>$customer['cid']))->save($save);
		
		LogTransactionModel::ModifyMoney('',$customer['cid'],'业绩分配',
				$customer['money'],$money * $oinfo['number'],$save['money'],"订单号[".$oinfo['order_no']."]");
		
		
		LogTransactionModel::ModifyInventory
			('', $oinfo[order_no], '订单业绩分配', 
			"分销商[{$customer[mobile]}/{$customer[name]}]业绩分配金额：{$money} * {$oinfo['number']}。积分：{$point} * {$oinfo['number']}");
	}
	
	function UserAward($user,$oinfo,$money,$point){
	
		$oc = M("csl_user");
	
		$save['money'] = $user['money'] + $money * $oinfo['number'];
		$save['point'] = $user['point'] + $point * $oinfo['number'];
		$oc->where(array('uid'=>$user['uid'],'status'=>'1'))->save($save);
	
		LogTransactionModel::ModifyMoney($user['uid'],'','业绩分配',
				$user['money'],$money * $oinfo['number'],$save['money'],"订单号[".$oinfo['order_no']."]");
		
		
		LogTransactionModel::ModifyInventory
			('', $oinfo[order_no], '订单业绩分配',
			"代理商[{$user[username]}/{$user[name]}]业绩分配金额：{$money} * {$oinfo['number']}。积分：{$point} * {$oinfo['number']}");
	}
	
	function UserCityAward($user,$oinfo,$money,$point){
	
		$oc = M("csl_user");
	
		$save['money'] = $user['money'] + $money * $oinfo['number'];
		$save['point'] = $user['point'] + $point * $oinfo['number'];
		$oc->where(array('uid'=>$user['uid'],'status'=>'1'))->save($save);
	
		LogTransactionModel::ModifyMoney($user['uid'],'','业绩分配',
				$user['money'],$money * $oinfo['number'],$save['money'],"订单号[".$oinfo['order_no']."]");
	
	
		LogTransactionModel::ModifyInventory
		('', $oinfo[order_no], '订单业绩分配',
				"代理商[{$user[username]}/{$user[name]}][{$user[city]}][跨区订单]业绩调整金额：{$money} * {$oinfo['number']}。");
	}
	
	
	private function OrderPaySuccess($order_no,$paytype,$amount,$data){
		$ob = M("csl_order");
		$info = $ob->where(array("order_no"=>$order_no))->find();
		if ($info){
			if ($info["order_status"] == "7"){  //已经支付过
				return true;
			}else{
				$map["order_status"] = "7";
				$ob->where(array("order_no"=>$order_no))->save($map);
	
				file_get_contents('http://www.25mp.cn/OrderCheck/OrderCheck/order_no/'.$data["out_trade_no"]);
	
				$payment = M("csl_payment");
				$content["order_no"] = $order_no;
				$content["cid"] = $info["cid"];
				$content["bank"] = $paytype;
				$content["money"] = $amount;
				$content["ip"] = $_SERVER["REMOTE_ADDR"];
				$content["ctime"] = date("Y-m-d H:i:s", time());
				$content["serialize"] = '';
				$payment->add($content);
	
				$log = M("log_transaction");
				$content2["order_no"] = $data["out_trade_no"];
				$content2["uid"] = $info["uid"];
				$content2["action"] = $paytype;
				$content2["msg"] = "支付金额:".$amount;
				$content2["session"] = session_id();
				$content2["ctime"] =  date("Y-m-d H:i:s", time());
				$log->add($content2);
				return true;
			}
		}else{
			return false;
		}
	}
	
	
	
	
	
	
	
	
	
	/*
	 * 特殊订单支付
	 * 
	 */
	function NotifySpecialOrder(){
		$logHandler= new CLogFileHandler(LOG_PATH."/Pay-".date('Y-m').'.log');
		$log = PayLog::Init($logHandler, 15);
	
		$notify = new PaySpecialOrderNotifyCallBack();
		$notify->Handle(false);
	}
	
}




/*
 * 订单支付验证类
 */
class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		if(array_key_exists("return_code", $result)
				&& array_key_exists("result_code", $result)
				&& $result["return_code"] == "SUCCESS"
				&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg){
			
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		
		
		$ob = M("csl_order");
		$info = $ob->where(array("order_no"=>$data["out_trade_no"]))->find();
		
		if ($info){
			if ($info["order_status"] >= 7){  //已经支付过
				return true;
			}else{
				$map["order_status"] = "7";
				$ob->where(array("order_no"=>$data["out_trade_no"]))->save($map);
				
				file_get_contents('http://www.25mp.cn/OrderCheck/OrderCheck/order_no/'.$data["out_trade_no"]);
				
				$payment = M("csl_payment");
				$content["order_no"] = $data["out_trade_no"];
				$content["cid"] = $info["cid"];
				$content["bank"] = "微信支付";
				$content["money"] = $data["total_fee"]/100;
				$content["ip"] = $_SERVER["REMOTE_ADDR"];
				$content["ctime"] = date("Y-m-d H:i:s", time());
				$content["serialize"] = $ser;
				$payment->add($content);
				
				//日志记录
				$log = M("log_transaction");
				$content2["order_no"] = $data["out_trade_no"];
				$content2["uid"] = $info["uid"];
				$content2["action"] = "微信支付";
				$content2["msg"] = "微信支付金额:".$data["total_fee"]/100;
				$content2["session"] = session_id();
				$content2["ctime"] =  date("Y-m-d H:i:s", time());
				$log->add($content2);
				
				return true;
			}
		}else{
			return false;
		}
		
	}
	
	
}


/*
 * 特殊商品支付类
 */
class PaySpecialOrderNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		// 		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
				&& array_key_exists("result_code", $result)
				&& $result["return_code"] == "SUCCESS"
				&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg){
		// 		PayLog::DEBUG("call back:" . json_encode($data));
			
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			PayLog::DEBUG("WxPayNotify OrderCheck NotifyProcess: 输入参数不正确");
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			PayLog::DEBUG("WxPayNotify OrderCheck NotifyProcess: 订单查询失败");
			return false;
		}

		PayLog::DEBUG("正在处理特殊订单号:" . ($data['out_trade_no']));

		$ob = M("csl_special_order");
		$info = $ob->where(array("order_no"=>$data["out_trade_no"]))->find();


		if ($info){
			if ($info["order_status"] >= 7){  //已经支付过
				return true;
			}else{
				$map["order_status"] = 7;
				$ob->where(array("order_no"=>$data["out_trade_no"]))->save($map);

				$payment = M("csl_payment");
				$content["order_no"] = $data["out_trade_no"];
				$content["cid"] = $info["cid"];
				$content["bank"] = "微信支付";
				$content["money"] = $data["total_fee"]/100;
				$content["ip"] = $_SERVER["REMOTE_ADDR"];
				$content["ctime"] = date("Y-m-d H:i:s", time());
				$content["serialize"] = $ser;
				$payment->add($content);

				$log = M("log_transaction");
				$content2["order_no"] = $data["out_trade_no"];
				$content2["uid"] = $info["uid"];
				$content2["action"] = "微信支付";
				$content2["msg"] = "微信支付金额:".$data["total_fee"]/100;
				$content2["session"] = session_id();
				$content2["ctime"] =  date("Y-m-d H:i:s", time());
				$log->add($content2);

				return true;
			}
		}else{
			return false;
		}

	}


}